package directory

import (
	"context"
	// "fmt"

	"mall/common/globalkey"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/logic/media/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils"
	"mall/service/backend/api/internal/utils/parse"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetDirectoryListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetDirectoryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDirectoryListLogic {
	return &GetDirectoryListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDirectoryListLogic) GetDirectoryList(req *types.MediaFileListReq) (resp *types.MediaFileListResp, err error) {
	// logrus.Info(fmt.Sprintf("MediaFileListReq: %+v", req))

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var status uint32
	if req.Status != nil {
		status = *req.Status + 1
	}

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)

	data, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
		Page:     page,
		PageSize: pageSize,
		ParentId: req.ParentId,
		AltText:  req.Title,
		Path:     req.Path,
		Type:     pointy.GetPointer(uint32(globalkey.AttachmentTypeDirectory)),
		Status:   &status,
		OrderBy:  orderBys,
		FilterBy: filterBys,
	})
	if err != nil {
		return nil, err
	}

	resp = &types.MediaFileListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.MediaFileListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}

	for _, v := range data.List {
		option := utils.GetOptionByStatus(v.Status)
		resp.Data.List = append(resp.Data.List, &types.MediaFileInfo{
			BaseUUIDInfo: types.BaseUUIDInfo{
				Id:         v.Id,
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			UserId:   v.UserId,
			ParentId: v.ParentId,
			Title:    v.AltText,
			Excerpt:  v.Excerpt,
			FileType: v.Type,
			Status:   v.Status,
			Sort:     v.Sort,
			Path:     v.Filename,
			FullPath: v.Path,
		})
	}

	return resp, nil
}
